home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 10257 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.9 KB

  1. Path: keats.ugrad.cs.ubc.ca!not-for-mail
  2. From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: file pointer(buffering problem)
  5. Date: 15 Mar 1996 21:23:22 -0800
  6. Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
  7. Message-ID: <4idj8aINNr76@keats.ugrad.cs.ubc.ca>
  8. References: <4icaq9$1e@usc.edu>
  9. NNTP-Posting-Host: keats.ugrad.cs.ubc.ca
  10.  
  11. In article <4icaq9$1e@usc.edu>, ???
  12.  <cfong@sunset.usc.edu> wrote:
  13. > I hope you all can help me on this...
  14. > I was wondering if there is a way that I can read and write
  15. > a same file at the same time...  without buffering the old stuff
  16. > here is what I wanted to do:
  17. > a text file of thousand lines:
  18. > Jason Fong
  19. > ...
  20. > ..
  21. > .
  22. > All I wanted to change is the first line to:
  23. >
  24. > Jason
  25. > ...
  26. > ..
  27. > .
  28. > Is there a way that I can update the file without buffering the whole
  29. > file first!?!
  30.  
  31. Of course, but you have to copy to a new file.
  32.  
  33. This is what a stream editor does (the 'sed' program).
  34.  
  35. In sed, the above could be accomplished using (among other ways):
  36.  
  37.     sed -e '1s/ Fong//' < infile > outfile.
  38.  
  39. Sed reads its standard input, and performs the given command, which in this case
  40. addresses a single line (1, the first line), and tells it to do a regular
  41. expression substitution: change " Fong" to "". As it reads, it writes to
  42. standard output; in performing the above substitution, it will never buffer
  43. more than a couple of lines.
  44.  
  45. To get it to delete the first three lines, you might do:
  46.  
  47.     sed -e '1,3d' < infile > outfile
  48.  
  49. You can do the same thing in your C program. Read lines from one stream and
  50. copy to another. When you see the line you want, do the transformation.
  51.  
  52. To hide the fact that two files are used, use tmpnam() to create a temporary
  53. file name where you can copy the lines, and then remove() the original (or
  54. rename() it to a backup) and rename() the temporary one to the original name.  
  55. -- 
  56.  
  57.